package com.dingdang.service.impl;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.teaopenapi.models.Config;
import com.dingdang.service.SendMessagesServiceI;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
@Service
public class SendMessagesServiceImpl implements SendMessagesServiceI {
    @Resource
    private RedisTemplate redisTemplate;
    @Override
    public void sendMessage(String phone) {
        Client client = null;
        try {
            client = createClient("LTAI4GCbdwnjCGwQj9Z3tr3N", "27ih4pc1W1tqey9X4mmCy1JUotAX7L");
           //生成验证码
            String numeric = RandomStringUtils.randomNumeric(6);
//            将验证码存入redis中  ,以便校验
            redisTemplate.boundValueOps(phone).set(numeric,30, TimeUnit.MINUTES);
            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    .setPhoneNumbers(phone)//手机号
                    .setSignName("东科创想")
                    .setTemplateCode("SMS_162522027")
                    .setTemplateParam("{\"sms_code\":\""+ numeric + "\"}");//信息内容
            // 复制代码运行请自行打印 API 的返回值
            client.sendSms(sendSmsRequest);
        } catch (Exception e) {
            e.printStackTrace();

        }
    }

    public Client createClient (String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new Client(config);
    }


}
